<?php
/**
 * User: xuanbang.wen
 * Date: 2019/8/18
 */

namespace App\Web\Controller;

use App\Service\Dict;
use App\Service\DictConstant;
use App\Web\Facades\UserAuth;
use App\Web\Model\Attach;
use App\Web\Model\CaseModel;
use App\Web\Model\Customer as CustomerModel;
use App\Web\Model\CaseOperator as CaseOprModel;
use App\Web\Model\CustomerAccount as AccountModel;
use App\Web\Model\Project as ProjectModel;
use App\Web\Model\CaseOperator;
use App\Web\Model\User as UserModel;
use EchoPHP\Facades\Db;
use EchoPHP\Facades\Redis;
use EchoPHP\Facades\Validation;
use EchoPHP\Http\Request;
use EchoPHP\Http\Response\JsonResponse;
use EchoPHP\Validator\Validator;
use Exception;
use PHPExcel;
use PHPExcel_IOFactory;
use PhpOffice\PhpSpreadsheet\IOFactory;
use Ramsey\Uuid\Uuid;

class CaseInfo extends Controller {
    private $allowRowNum = 100;
    private $startRow = 6;
    private $listindexMap = [
        '高' => 1,
        '中' => 2,
        '低' => 3
    ];
    private $isSeparate = [
        '是' => 1,
        '否' => 0,
    ];
    private $caseCountMax = 100;        //项目下最大职位数

    public function batchEditCaseOpr(Request $request) {
        $params = [
            'caseids' => $request->getParam('caseids'),
            'oprids' => $request->getParam('oprids'),
        ];
        $isreplace = (bool)$request->getParam('isreplace', false);
        $caseModel = new CaseModel();
        return $this->json($caseModel->batchEditOpr($params, $isreplace));
    }

    public function recentCase() {
        $caseMap = $caseList = [];
        $caseModel = new CaseModel();
        $caseIds = $caseModel->getRecentCase(UserAuth::getLoginId());
        if (!$caseIds) {
            return $this->json(
                [
                    'status' => true,
                    'caselist' => [],
                    'projectlist' => []
                ]
            );
        }
        $caseInfo = $caseModel->getCaseInfoByCaseIds($caseIds);
        $projectList = $caseModel->getProjectInfoByProjectIds(array_column($caseInfo, 'projectid'));
        //以redis中的顺序排序
        foreach ($caseInfo as $case) {
            $caseMap[$case['caseid']] = $case;
        }
        foreach ($caseIds as $caseId) {
            $caseList [] = [
                'caseid' => $caseId,
                'projectid' => $caseMap[$caseId]['projectid'],
                'casename' => $caseMap[$caseId]['casename'],
                'subid' => $caseMap[$caseId]['subid'],
                'hascontact' => $caseMap[$caseId]['hascontact'],
                'haschargeway' => $caseMap[$caseId]['haschargeway'],
            ];
        }
        return $this->json(
            [
                'status' => true,
                'caselist' => $caseList,
                'projectlist' => $projectList
            ]
        );
    }

    //下载职位模板
    public function downloadCaseTmpl() {
        $caseTmpl = config('app.case_tempalte');
        return response()->download($caseTmpl, 'RPO职位批量添加模板.xlsx');
    }

    /**
     * Notes:上传职位模板并添加数据至相关表
     * @param Request $request
     * @return JsonResponse
     */
    public function batchCreateCase(Request $request) {
        $errList = $insertData = $allProjOpr = [];
        $uploadResult = $this->uploadExcel($request);
        if (is_array($uploadResult)) {
            return $this->json($uploadResult);
        }
        $objCase = IOFactory::load($uploadResult);
        $sheet = $objCase->getSheet(0);
        $maxRow = $sheet->getHighestRow(); //获取最大行数
        $endRow = $maxRow > ($this->allowRowNum + $this->startRow) ? $this->allowRowNum + $this->startRow : $maxRow;
        $userid = $this->getLoginId();
        $allUserIds = (new UserModel())->getAllUserId();
        $dict = new Dict();
        $dict->setLang('zh');
        $areaDict = $dict->all('jobarea');
        for ($row = $this->startRow; $row <= $endRow; $row++) {
            $No = trim($sheet->getCellByColumnAndRow(1, $row)->getValue());
            $subId = trim($sheet->getCellByColumnAndRow(2, $row)->getValue());
            if (!$subId) {
                break;
            }
            $projectId = trim($sheet->getCellByColumnAndRow(3, $row)->getValue());
            if (!$projectId) {
                $errList[] = [
                    'No' => $No,
                    'errorMsg' => '项目id不能为空'
                ];
                continue;
            }
            $casename = trim($sheet->getCellByColumnAndRow(4, $row)->getValue());
            if (!$casename) {
                $errList[] = [
                    'No' => $No,
                    'errorMsg' => '职位名称不能为空'
                ];
                continue;
            } elseif (mb_strlen($casename) > 200) {
                $errList[] = [
                    'No' => $No,
                    'errorMsg' => '职位名称最多200字'
                ];
            }
            $caseshowname = trim($sheet->getCellByColumnAndRow(5, $row)->getValue());
            if (!$caseshowname) {
                $errList[] = [
                    'No' => $No,
                    'errorMsg' => '职位展示名称不能为空'
                ];
                continue;
            } elseif (mb_strlen($caseshowname) > 200) {
                $errList[] = [
                    'No' => $No,
                    'errorMsg' => '职位展示名称最多200字'
                ];
                continue;
            }
            $area = trim($sheet->getCellByColumnAndRow(8, $row)->getValue());
            $area = formatIdsToArr($area);
            if (!$area) {
                $errList[] = [
                    'No' => $No,
                    'errorMsg' => '地区不能为空'
                ];
                continue;
            } elseif (count($area) > 5) {
                $errList[] = [
                    'No' => $No,
                    'errorMsg' => '地区最多支持5个'
                ];
                continue;
            }
            foreach ($area as $key=>$item){
                $res = array_search($item, $areaDict);
                //中文,转化为code
                if ($res){
                    $area[$key] = $res;
                //code,简单验证
                }elseif (6 != strlen($item)) {
                    $errList[] = [
                        'No' => $No,
                        'errorMsg' => '地区码非法'
                    ];
                    continue 2;
                }
            }

            $oprIds = trim($sheet->getCellByColumnAndRow(11, $row)->getValue());
            $oprIds = formatIdsToArr($oprIds);
            if (count($oprIds) > 50) {
                $errList[] = [
                    'No' => $No,
                    'errorMsg' => '协作人最多支持50个'
                ];
                continue;
            } else if (!empty(array_diff($oprIds, $allUserIds))) {
                $errList[] = [
                    'No' => $No,
                    'errorMsg' => '职位协作人id非法'
                ];
                continue;
            }
            $separate = trim($sheet->getCellByColumnAndRow(9, $row)->getValue());
            if (!isset($this->isSeparate[$separate])) {
                $errList[] = [
                    'No' => $No,
                    'errorMsg' => '拆分为多个职位非法'
                ];
                continue;
            } else {
                $separate = $this->isSeparate[$separate];
            }
//            $duedate = trim($sheet->getCellByColumnAndRow(8, $row)->getValue());
//            if ($duedate != date('Y-m-d', strtotime($duedate))) {
//                $errList[] = [
//                    'No' => $No,
//                    'errorMsg' => '截止日期错误'
//                ];
//                continue;
//            } elseif ($duedate <= date('Y-m-d')) {
//                $errList[] = [
//                    'No' => $No,
//                    'errorMsg' => '过期时间需大于等于明天'
//                ];
//                continue;
//            }
            $salaryfrom = trim($sheet->getCellByColumnAndRow(6, $row)->getValue());
            $salaryto = trim($sheet->getCellByColumnAndRow(7, $row)->getValue());

            if ($salaryfrom > 2000000000 || $salaryto > 2000000000) {
                $errList[] = [
                    'No' => $No,
                    'errorMsg' => '薪资不能超过2000000000万'
                ];
                continue;
            } elseif ($salaryfrom > $salaryto) {
                $errList[] = [
                    'No' => $No,
                    'errorMsg' => '顶薪不能小于起薪'
                ];
                continue;
            } elseif (!is_numeric($salaryfrom) || !is_numeric($salaryto) || empty($salaryfrom) || empty($salaryto)) {
                $errList[] = [
                    'No' => $No,
                    'errorMsg' => '非法薪资'
                ];
                continue;
            }

            $listindex = trim($sheet->getCellByColumnAndRow(10, $row)->getValue());
            if (!isset($this->listindexMap[$listindex])) {
                $errList[] = [
                    'No' => $No,
                    'errorMsg' => '优先级非法'
                ];
                continue;
            } else {
                $listindex = $this->listindexMap[$listindex];
            }
            $content = trim($sheet->getCellByColumnAndRow(12, $row)->getValue());
            $length = mb_strlen($content);
            if ($length > 4000) {
                $errList[] = [
                    'No' => $No,
                    'errorMsg' => '职位描述最多4000字'
                ];
                continue;
            }
            $vacancy = (int)trim($sheet->getCellByColumnAndRow(13, $row)->getValue());
            if ($vacancy > 2000000000 || $vacancy <= 0) {
                $errList[] = [
                    'No' => $No,
                    'errorMsg' => '需求人数为1至2000000000'
                ];
                continue;
            }
            $insertData [] = [
                //'uuid' => Uuid::uuid1()->toString(),
                'No' => $No,
                'subid' => $subId,
                'projectid' => $projectId,
                'casename' => $casename,
                'caseshowname' => $caseshowname,
                'salaryfrom' => $salaryfrom,
                'salaryto' => $salaryto,
                'area' => $area,//implode(',', $area),
                'separate' => $separate,
                'content' => $content,
                'creator' => $userid,
                'updator' => $userid,
//                'duedate' => $duedate,
                'listindex' => $listindex,
                'oprid' => $oprIds,
                'vacancy' => $vacancy,
            ];
        }

        $projectModel = new ProjectModel();
        $projectIds = array_column($insertData, 'projectid');

        //检查subid 和 projectid 合法性
        $subList = $projectModel->chkProjectId($projectIds);
        // 检查projectid，并将项目负责人添加至职位协作人
        $projectOperators = $projectModel->operatorList($projectIds);
        $caseCount = (new CaseModel())->getCaseCount();
        foreach ($insertData as $k => $item) {
            if (!isset($subList[$item['projectid']]) || $subList[$item['projectid']] != $item['subid']) {
                $errList[] = [
                    'No' => $item['No'],
                    'errorMsg' => '请检查客户与项目id是否正确且项目正在进行中'
                ];
                unset($insertData[$k]);
                continue;
            }
            if ($item['separate'] == false) {
                if (isset($caseCount[$item['projectid']]) && $caseCount[$item['projectid']] >= $this->caseCountMax) {
                    $errList[] = [
                        'No' => $item['No'],
                        'errorMsg' => '已达职位数上限，无法继续新增'
                    ];
                    unset($insertData[$k]);
                    continue;
                } else {
                    $caseCount[$item['projectid']] = isset($caseCount[$item['projectid']]) ? $caseCount[$item['projectid']] + 1 : 1;
                }
            } else {
                if (isset($caseCount[$item['projectid']]) && count($area) + $caseCount[$item['projectid']] > $this->caseCountMax) {
                    $errList[] = [
                        'No' => $item['No'],
                        'errorMsg' => '已达职位数上限，无法继续新增'
                    ];
                    unset($insertData[$k]);
                    continue;
                } else {
                    $caseCount[$item['projectid']] = isset($caseCount[$item['projectid']]) ? $caseCount[$item['projectid']] + count($area) : count($area);
                }
            }
            //当前用户加入职位
            $oprIds = array_merge($item['oprid'], [$userid]);
            $projectOperatorIds = array_column($projectOperators[$item['projectid']], 'userid');
            if (!in_array($userid, $projectOperatorIds)) {
                $errList[] = [
                    'No' => $item['No'],
                    'errorMsg' => '当前用户无为项目id：' . $item['projectid'] . ' 添加职位权限'
                ];
                unset($insertData[$k]);
                continue;
            }
            //项目执行人加入职位
            foreach ($projectOperators[$item['projectid']] as $projectOperator) {
                if ($projectOperator['ischarger'] == 1) {
                    $projectCharger = $projectOperator['userid'];
                    $oprIds[] = $projectCharger;
                }
            }
            $insertData[$k]['oprid'] = array_unique($oprIds);
        }
        if (!$insertData) {
            return $this->json([
                'status' => false,
                'message' => '无有效数据',
                'errList' => $errList
            ]);
        }
        $result = (new CaseModel())->batchCreate($insertData);
        $errList = array_merge($result['errorlist'], $errList);
        $insertCases = $result['insertcases'];
        $lastRow = $row - $this->startRow;
        $message = empty($errList) ? '共' . $lastRow . '条插入成功' : '共' . $lastRow . '条，失败' . count($errList) . '条';
        return $this->json([
            'status' => empty($errList),
            'message' => $message,
            'errList' => $errList,
            'insertcases' => $insertCases
        ]);
    }

    //批量职位的上传处理
    private function uploadExcel($request) {
        $validateRule = [
            'excel|附件' => [
                'required',
                'mimes' => ['xlsx', 'xls'],
//                'minSize' => 10,
//                'maxSize' => 1024*200,
            ]
        ];

        $validate = new Validator($validateRule);
        $file = $request->getFile('excel');
        $result = $validate->validate(['excel' => $file]);
        if (!$result) {
            return [
                'status' => false,
                'message' => '字段校验失败：' . current($validate->getErrors()),
            ];
        }
        $filename = $_FILES['excel']['tmp_name'];
        if (!file_exists($filename)) {
            return [
                'status' => false,
                'message' => '上传失败',
            ];
        }
        return $filename;
    }

    //批量修改状态
    public function batchEditStatus(Request $request) {
        $params = [
            'field' => 'status',
            'userid' => $this->getLoginId(),
            'value' => $request->getPost('status'),
            'caseids' => $request->getPost('caseids')
        ];
        //强类型验证
        if (!in_array((string)$params['value'], ['01', '02', '03'], true)) {
            return $this->json([
                'status' => false,
                'message' => 'status字段值非法'
            ]);
        }
        $result = (new CaseModel())->batchEdit($params);
        return $this->json($result);
    }

    //批量修改优先级
    public function batchEditPriority(Request $request) {
        $params = [
            'field' => 'listindex',
            'userid' => $this->getLoginId(),
            'value' => $request->getPost('listindex'),
            'caseids' => $request->getPost('caseids')
        ];
        if (!Validation::validateIn('listindex', $params['value'], [1, 2, 3])) {
            return $this->json([
                'status' => false,
                'message' => 'listindex字段值非法'
            ]);
        }
        $result = (new CaseModel())->batchEdit($params);
        return $this->json($result);
    }

    /**
     * Notes:公司项目列表（客户/项目对接人）
     * @return JsonResponse
     */
    public function subOprSubList() {
        $userid = $this->getLoginId();
        $caseModel = new CaseModel();
        $subList = $caseModel->subOprSub($userid);
        return $this->json(
            [
                'status' => true,
                'message' => '获取成功',
                'subList' => $subList
            ]
        );
    }

    /**
     * 职位管理、人才管理 查询客户列表
     * @param Request $request
     * @return JsonResponse
     * @throws Exception
     */
    public function getSubList(Request $request) {
        $oprId = $this->getLoginId();
        $subName = $request->getParam('subname');
        $projectName = $request->getParam('projectname');

        $caseModel = new CaseModel();
        $subList = $caseModel->getSubList($oprId, $subName, $projectName);
        return $this->json(
            [
                'status' => true,
                'message' => '获取成功',
                'subList' => $subList
            ]
        );
    }

    /**
     * 根据客户id获取客户下项目列表
     * @param Request $request
     * @return JsonResponse
     * @throws Exception
     */
    public function getProjectList(Request $request) {
        $oprId = $this->getLoginId();
        $subId = $request->getParam('subid');
        $isFinished = $request->getParam('isfinished', 0);
        $projectName = $request->getParam('projectname');

        $caseModel = new CaseModel();
        $projectList = $caseModel->getProjectListBySubId($oprId, $subId, $isFinished, $projectName);
        return $this->json(
            [
                'status' => true,
                'message' => '获取成功',
                'projList' => $projectList
            ]
        );
    }

    /**
     * 职位管理页列表
     * @param Request $request
     * @return JsonResponse
     * @throws Exception
     */
    public function getCaseList(Request $request) {
        $oprId = $this->getLoginId();
        $projectId = $request->getParam('projectid');
        $caseModel = new CaseModel();
        $caseList = $caseModel->getCaseListByProjectId($oprId, $projectId);
        return $this->json(
            [
                'status' => true,
                'message' => '获取成功',
                'caseList' => $caseList
            ]
        );
    }

    /**
     * 获取职位管理页项目统计数据
     * @param Request $request
     * @return JsonResponse
     * @throws Exception
     */
    public function projectCountInfo(Request $request) {
        $userId = $this->getLoginId();
        $projectId = $request->getParam('projectId');
        $caseModel = new CaseModel();
        $projectCaseCount = $caseModel->getProjectCaseAndOprCount($userId, $projectId);
        return $this->json(
            [
                'status' => true,
                'message' => '获取成功',
                'cardInfo' => $projectCaseCount
            ]
        );
    }

    /**
     * Notes:创建职位
     * @param Request $request
     * @return JsonResponse
     */
    public function create(Request $request) {
        $params = [
            'projectid' => $request->getPost('projectid'),
            'casename' => $request->getPost('casename'),
            'salaryfrom' => $request->getPost('salaryfrom'),
            'salaryto' => $request->getPost('salaryto'),
            'area' => $request->getPost('area'),
            'separate' => $request->getPost('separate', 0),
            'content' => $request->getPost('content'),
            //'duedate' => $request->getPost('duedate'),
            'oprid' => $request->getPost('oprid'),
            'attachid' => $request->getPost('attachid', 0),
            'listindex' => $request->getPost('listindex'),
            'caseshowname' => $request->getPost('caseshowname'),
            'vacancy' => $request->getPost('vacancy')
        ];
        $projectInfo = (new ProjectModel())->getProjectInfo($params['projectid'], 'subid');
        $subid = $projectInfo['subid'] ?? 0;
        if (!$subid) {
            return $this->json([
                'status' => false,
                'message' => '字段校验失败',
                'validateFailure' => ['projectid' => '项目id错误']
            ]);
        }
        $params['subid'] = $subid;
        $rule = [
//            'oprid|职位协作人id' => [
//                'required'
//            ],
            'subid|交易公司id' => [
                'required', 'number'
            ],
            'projectid|交易公司项目id' => [
                'required', 'number'
            ],
            'casename|职位名称' => [
                'required', 'maxLength' => 200
            ],
            'salaryfrom|起薪' => [
                'required', 'number'
            ],
            'salaryto|顶薪' => [
                'required', 'number', 'Max' => 2000000000
            ],
            'area|工作地点' => [
                'required',
            ],
            'content|职位描述' => [
                'required', 'maxLength' => 4000
            ],
//            'duedate|过期时间' => [
//                'required', 'dateFormat' => 'Y-m-d', 'After' => date("Y-m-d")
//            ],
            'listindex|优先级' => [
                'required', 'in' => '1,2,3'
            ],
            'caseshowname|职位显示名称' => [
                'required', 'maxLength' => 200
            ],
            'vacancy|需求人数' => [
                'required', 'number', 'Max' => 2000000000, 'Min' => 1
            ],
        ];
        $msg = [
//            'duedate.dateFormat' => '过期时间格式不正确',
//            'duedate.After' => '过期时间需大于等于明天',
            'salaryto.Max' => '顶薪需小于2000000000',
            'vacancy' => '需求人数为1至2000000000'
        ];
        $validate = new Validator($rule, $msg);
        if (!$validate->validate($params)) {
            return $this->json([
                'status' => false,
                'message' => '字段校验失败',
                'validateFailure' => $validate->getErrors()
            ]);
        }
        if ($params['salaryto'] < $params['salaryfrom']) {
            return $this->json([
                'status' => false,
                'message' => '字段校验失败',
                'validateFailure' => ['salaryfrom' => '起薪需小于顶薪']
            ]);
        }
        $caseModel = new CaseModel();
        $result = $caseModel->create($subid, $params['projectid'], $params);
        return $this->json($result);
    }

    public function getInfo(Request $request) {
        $caseModel = new CaseModel();
        $CaseOprModel = new CaseOprModel();
        $oprId = $this->getLoginId();
        $caseid = $request->getParam('caseid');
        $case = $caseModel->getInfoByCaseId($oprId, $caseid);
        if (!$case) {
            return $this->json(
                [
                    'status' => false,
                    'message' => '职位不存在或您无权查看',
                    'caseinfo' => [],
                ]
            );
        }
        $operator = $CaseOprModel->getOpr($caseid);
        $attributes = [
            'area' => [DictConstant::DD_CITY_COUNTY, '']
        ];

        $dict = new Dict();
        $dict->rowTrans($case, $attributes, true, ',', '/');
        $case ['salary'] = $case['salaryfrom'] . '至' . $case['salaryto'] . '万/年';
        $case['operator'] = $operator;
        $case['listindex_zn'] = array_flip($this->listindexMap)[$case['listindex']];
        $case['createdate'] = date('Y-m-d', strtotime($case['createdate']));
        $case['userid'] = UserAuth::getLoginId();
        $case['iscaseopr'] = in_array(UserAuth::getLoginId(), array_column($operator, 'userid'));
        $projectModel = new ProjectModel();
        $case['isprojectcharger'] = $projectModel->chkEditRight($case['projectid']) ? 1 : 0;
        $customerModel = new CustomerModel();
        $case['issubcharger'] = $customerModel->chkEditSubRight($case['subid']) ? 1 : 0;
        $projectCharger = $projectModel->getProjectOpr($case['subid'], $case['projectid'], 1);
        $case['projectcharger'] = $projectCharger[0]['oprid'] ?? 0;
        return $this->json(
            [
                'status' => true,
                'message' => '获取成功',
                'caseinfo' => $case,
            ]
        );
    }

    /**
     * Notes:修改职位
     * @param Request $request
     * @return JsonResponse
     */
    public function edit(Request $request) {
        $caseModel = new CaseModel();
        $params = [
            'caseid' => $request->getPost('caseid'),
            'casename' => $request->getPost('casename'),
            'salaryfrom' => $request->getPost('salaryfrom'),
            'salaryto' => $request->getPost('salaryto'),
            'area' => $request->getPost('area'),
            'content' => $request->getPost('content'),
            //'duedate' => $request->getPost('duedate'),
            'vacancy' => $request->getPost('vacancy'),
            'listindex' => $request->getPost('listindex'),
            'oprids' => $request->getPost('oprids', []),
            'caseshowname' => $request->getPost('caseshowname')
        ];
        $rule = [
            'caseid|职位id' => [
                'required', 'number'
            ],
            'casename|职位名称' => [
                'required', 'maxLength' => 200
            ],
            'salaryfrom|起薪' => [
                'required', 'number'
            ],
            'salaryto|顶薪' => [
                'required', 'number', 'Max' => 2000000000
            ],
            'area|工作地点' => [
                'required',
            ],
            'content|职位描述' => [
                'required', 'maxLength' => 4000
            ],
//            'status|职位状态' => [
//                'required',
//            ],
//            'duedate|过期时间' => [
//                'required', 'dateFormat' => 'Y-m-d', 'After' => date("Y-m-d")
//            ],
            'listindex|优先级' => [
                'required', 'number', 'in' => '1,2,3'
            ],
            'oprids|职位协作人id' => [
//                'required',
            ],
            'caseshowname|职位显示名称' => [
                'required', 'maxLength' => 200
            ],
            'vacancy|需求人数' => [
                'required', 'number', 'Max' => 2000000000, 'Min' => 1
            ],
        ];
        $msg = [
//            'duedate.dateFormat' => '过期时间格式不正确',
//            'duedate.After' => '过期时间需大于等于明天',
            'salaryto.Max' => '顶薪需小于2000000000',
            'vacancy' => '需求人数为1至2000000000'
        ];
        $validate = new Validator($rule, $msg);
        if (!$validate->validate($params)) {
            return $this->json([
                'status' => false,
                'message' => '字段校验失败',
                'validateFailure' => $validate->getErrors()
            ]);
        }
        if ($params['salaryto'] < $params['salaryfrom']) {
            return $this->json([
                'status' => false,
                'message' => '字段校验失败',
                'validateFailure' => ['salary' => '起薪需小于等于顶薪']
            ]);
        }
        $userid = $this->getLoginId();
        // 地区去重
        $params['area'] = implode(array_unique(explode(',', $params['area'])), ',');
        $params['updator'] = $userid;
        $params['oprids'] = array_unique($params['oprids']);
        //只有操作人可以修改
        $oprCaseList = (new CaseOperator())->chkMultiCaseOprRight($userid, [$params['caseid']]);
        if (!isset($oprCaseList[$params['caseid']])) {
            return $this->json([
                'status' => false,
                'message' => '无操作权限'
            ]);
        }

        $params['projectid'] = $oprCaseList[$params['caseid']]['projectid'];
        $params['subid'] = $oprCaseList[$params['caseid']]['subid'];

        $result = $caseModel->edit($params['caseid'], $userid, $params);
        return $this->json($result);
    }

    public function editOpr(Request $request) {
        $params = [
            'oprids' => $request->getPost('oprids'),
            'caseid' => $request->getPost('caseid'),
        ];
        //只有操作人可以修改
        $oprCaseList = (new CaseOperator())->chkMultiCaseOprRight(UserAuth::getLoginId(), [$params['caseid']]);
        if (!isset($oprCaseList[$params['caseid']])) {
            return $this->json([
                'status' => false,
                'message' => '无操作权限'
            ]);
        }
        $message = (new CaseModel())->editOpr($params);
        return $this->json([
            'status' => true,
            'message' => $message
        ]);
    }

    /**
     * 将交易公司在列表中置顶 或 取消置顶
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function topSub(Request $request) {
        $oprId = UserAuth::getLoginId();
        $subId = $request->getPost('subid/s');
        $status = $request->getPost('status', 1);//置顶 或 取消置顶
        $caseModel = new CaseModel();
        $result = $caseModel->topSub($oprId, $subId, $status);
        return $this->json($result);
    }

    /**
     * 职位选择沟通表头  已定义则更新，未定义则添加
     * @param Request $request
     * @return JsonResponse
     * @throws Exception
     */
    public function setCaseContactField(Request $request) {
        $caseId = $request->getPost('caseid', 0);
        $fieldIdList = $request->getPost('fieldidlist', ''); //沟通表头用字符串表示，逗号隔开 ，交付方式 id
        $caseModel = new CaseModel();
        $result = $caseModel->setCaseContactField($caseId, $fieldIdList);
        return $this->json($result);
    }

    /**
     * 未定义时职位选择沟通表头
     * @param Request $request
     * @return JsonResponse
     * @throws Exception
     */
    public function setCaseContactField2(Request $request) {
        $caseId = $request->getPost('caseid', 0);
        $fieldIdList = $request->getPost('fieldidlist', ''); //沟通表头用字符串表示，逗号隔开 ，交付方式 id
        $caseModel = new CaseModel();
        $result = $caseModel->setCaseContactField2($caseId, $fieldIdList);
        return $this->json($result);
    }

    /**
     * 职位选择交付方式  已定义则更新，未定义则添加
     * @param Request $request
     * @return JsonResponse
     * @throws Exception
     */
    public function setCaseChargeWay(Request $request) {
        $caseId = $request->getPost('caseid', 0);
        $chargeStandardIds = $request->getPost('chargestandardid', ''); // 收费标准id ,多个用逗号隔开
        $caseModel = new CaseModel();
        $result = $caseModel->setCaseChargeWay($caseId, $chargeStandardIds);
        return $this->json($result);
    }

    /**
     * 获取职位沟通表头列表
     * @param Request $request
     * @return JsonResponse
     * @throws Exception
     */
    public function getCaseContactField(Request $request) {
        $caseId = $request->getParam('caseid', 0);
        $withDetailInfo = $request->getParam('detail', 0);
        $keyCode = $request->getParam('keycode');
        $caseModel = new CaseModel();
        $result = $caseModel->getCaseContactFieldList($caseId, $withDetailInfo, $keyCode);
        return $this->json($result);
    }

    /**
     * 获取职位沟通表头列表--项目
     * @param Request $request
     * @return JsonResponse
     * @throws Exception
     */
    public function getCaseContactFieldListByProject(Request $request) {
        $caseId = $request->getParam('caseid', 0);
        $withDetailInfo = $request->getParam('detail', 0);
        $keyCode = $request->getParam('keycode');
        $caseModel = new CaseModel();
        $result = $caseModel->getCaseContactFieldListByProject($caseId, $withDetailInfo, $keyCode);
        return $this->json($result);
    }

    /**
     * 获取职位交付方式信息
     * @param Request $request
     * @return JsonResponse
     * @throws Exception
     */
    public function getCaseChargeWay(Request $request) {
        $caseId = $request->getParam('caseid', 0);
        $caseModel = new CaseModel();
        $result = $caseModel->getCaseChargeWay($caseId);
        return $this->json($result);
    }

    /**
     * 获取客户下所有有编辑权限的职位列表
     * @param Request $request
     * @return JsonResponse
     * @throws Exception
     */
    public function getActiveSubCaseList(Request $request) {
        $accountId = $request->getParam('accountid');
        $subId = $request->getParam('subid');
        $pageNum = $request->getParam('pagenum/d', 1);
        $pageLimit = $request->getParam('pageLimit/d', 50);
        $caseName = $request->getParam('casename');
        $projectName = $request->getParam('projectname');
        $projectId = $request->getParam('projectid');
        $caseModel = new CaseModel();
        $loginInfo = UserAuth::getLoginInfo();
        //加入当前查询页码
        list($pageNum, $rowFrom, $rowTo) = $caseModel->paginationParameters($pageNum, $pageLimit);

        if ($loginInfo['issuper'] == 1) {
            $caseList = $caseModel->getSubCaseList($subId ,$rowFrom, $rowTo,$pageNum,$caseName, $projectName,$projectId);
        } else if ($loginInfo['teamrole'] == 1) {
            $caseList = $caseModel->getActiveSubCaseListByOprId($subId,$loginInfo['userid'],$rowFrom, $rowTo,$pageNum,$caseName, $projectName,$projectId);
        } else {
            $caseList = $caseModel->getActiveSubCaseListByTeamCode($subId,$loginInfo['teamcode'],$rowFrom, $rowTo,$pageNum,$caseName, $projectName,$projectId);
        }
        //查询该联系人已作为职位联系人的职位
        $sql = 'select id as caseaccountid , caseid from CaseContacter where accountid = ? and status = ?';
        $var = [$accountId,'01'];
        $caseIdArr = Db::select($sql,$var);
        $caseIds = [];
        if(!empty($caseIdArr)) {
            foreach ($caseIdArr as $item) {
                $caseIds[$item['caseid']] = ['caseaccountid' => $item['caseaccountid'] ,'caseid' => $item['caseid']];
            }
        }
        $caseIdTmp = array_keys($caseIds);
        foreach ($caseList['subcaselist'] as &$case) {
            if(in_array($case['caseid'],$caseIdTmp)) {
                $case['iscasecontacter'] = 1;
                $case['caseaccountid'] = $caseIds[$case['caseid']]['caseaccountid'];
            } else {
                $case['iscasecontacter'] = 0;
                $case['caseaccountid'] = '';
            }
        }
        return $this->json($caseList);
    }

    /**
     * 将联系人批量添加到多个职位中
     * @param Request $request
     * @return JsonResponse
     * @throws Exception
     */
    public function batchAddContactor(Request $request){
        $contactorId = $request->getPost('contactorid');
        $caseIds = $request->getPost('caseids'); //多个字符串逗号隔开

        $caseModel = new CaseModel();
        $result = $caseModel->batchAddContactor($caseIds,$contactorId);
        return $this->json($result);
    }

    /**
     * 职位详情页添加客户联系人
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function addInterviewerInPeople(Request $request) {
        $params = [
            'email' => $request->getParam('email'),
            'caseid' => $request->getParam('caseid'),
            'cname' => $request->getParam('cname'),
            'memo' => $request->getParam('memo'),
            'department' => $request->getParam('department'),
            'mobilephone' => $request->getParam('mobilephone'),
            'isinterviewer' => $request->getParam('isinterviewer')
        ];
        if (empty($params['caseid'])) {
            return $this->json([
                'status' => false,
                'message' => '字段校验失败',
                'validateFailure' => '职位id不能为空'
            ]);
        }
        $accountModel = new AccountModel();
        $checkResult = $accountModel->addContactorDataCheck($params);
        if ($checkResult['status'] == false) {
            return $this->json($checkResult);
        }
        $params['mobilephone'] = ltrim($params['mobilephone'], '+');
        $phoneArr = explode("-", $params['mobilephone']);
        if (count($phoneArr) == 2) {
            if ($phoneArr[0] == 86) {
                $params['mobilephone'] = $phoneArr[1];
            } else {
                // $params['mobilephone'] = ltrim($params['mobilephone'], 0);
            }
        }
        $sql = 'select subid,projectid from SCase where caseid = ?';
        $var = [$params['caseid']];
        $caseInfo = Db::selectOne($sql,$var);
        if (empty($caseInfo)) {
            return $this->json(['status' => false, 'message' => '职位信息错误']);
        }
        //是否是职位协作人
        $caseModel = new CaseModel();
        $checkResult1 = $caseModel->chkCaseEditRight($params['caseid']);
        $projectModel = new ProjectModel();
        $checkResult2 = $projectModel->chkEditRight($caseInfo['projectid']);
        $customerModel = new CustomerModel();
        $checkResult3 = $customerModel->chkEditSubRight($caseInfo['subid']);
        if (!$checkResult1 && !$checkResult2 && !$checkResult3) {
            return $this->json(['status' => false, 'message' => '您无权新增客户联系人']);
        }

        $params['subid'] = $caseInfo['subid'];
        $result = $accountModel->add($params);
        return $this->json($result);
    }

    /**
     * 职位详情页编辑客户联系人
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function editCustomerAccount(Request $request) {
        $params = [
            'accountid' => $request->getParam('accountid'),
            'email' => $request->getParam('email'),
            'cname' => $request->getParam('cname'),
            'caseid' => $request->getParam('caseid'),
            'memo' => $request->getParam('memo'),
            'department' => $request->getParam('department'),
            'mobilephone' => $request->getParam('mobilephone'),
            'isinterviewer' => $request->getParam('isinterviewer',0)
        ];
        $rule = [
            'accountid|客户账户id' => [
                'required', 'number'
            ],
            'email|客户账户邮箱' => [
                'required', 'email'
            ],
            'caseid|职位id' => [
                'required', 'number'
            ],
            'cname|客户账户名称' => [
                'required', 'maxLength' => 50
            ],
            'mobilephone|面试官手机' => [
                'required', 'minLength' => 7, 'maxLength' => 19
            ],
            'department|部门' => [
                'maxLength' => 50
            ],
            'memo|备注' => [
                'maxLength' => 200
            ],
        ];
        $validate = new Validator($rule);
        if (!$validate->validate($params)) {
            return $this->json([
                'status' => false,
                'message' => '字段校验失败',
                'validateFailure' => $validate->getErrors()
            ]);
        }
        if ((preg_match('/(^(((\+)?\d{1,4}-)\d{5,15}$)|(^1\d{10}$))/', $params['mobilephone']) == 0) && (preg_match('/^((\(\d{2,3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?(\(0\d{2,3}\)|0\d{2,3})?(\(0\d{2,3}\)|0\d{2,3})?[1-9]\d{6,7}(\-\d{1,5})?$/', $params['mobilephone']) == 0)) {
            return $this->json([
                'status' => false,
                'message' => '字段校验失败',
                'validateFailure' => ['mobilephone' => '手机/座机格式不正确']
            ]);
        }
        $params['mobilephone'] = ltrim($params['mobilephone'], '+');
        $phoneArr = explode("-", $params['mobilephone']);
        if (count($phoneArr) == 2) {
            if ($phoneArr[0] == 86) {
                $params['mobilephone'] = $phoneArr[1];
            } else {
                // $params['mobilephone'] = ltrim($params['mobilephone'], 0);
            }
        }
        $sql = 'select subid,projectid from SCase where caseid = ?';
        $var = [$params['caseid']];
        $caseInfo = Db::selectOne($sql,$var);
        if (empty($caseInfo)) {
            return $this->json(['status' => false, 'message' => '职位信息错误']);
        }
        //是否是职位协作人
        $caseModel = new CaseModel();
        $checkResult1 = $caseModel->chkCaseEditRight($params['caseid']);
        $projectModel = new ProjectModel();
        $checkResult2 = $projectModel->chkEditRight($caseInfo['projectid']);
        $customerModel = new CustomerModel();
        $checkResult3 = $customerModel->chkEditSubRight($caseInfo['subid']);
        if (!$checkResult1 && !$checkResult2 && !$checkResult3) {
            return $this->json(['status' => false, 'message' => '您无权编辑客户联系人']);
        }
        $params['subid'] = $caseInfo['subid'];
        return $this->json((new AccountModel())->edit($params));
    }

    /**
     * 职位详情页删除客户联系人时判断是否已被职位绑定
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function deleteCheck(Request $request) {
        $accountId = $request->getParam('accountid');
        $caseId = $request->getParam('caseid');
        $sql = 'select subid,projectid from SCase where caseid = ?';
        $var = [$caseId];
        $caseInfo = Db::selectOne($sql,$var);
        if (empty($caseInfo)) {
            return $this->json(['status' => false, 'message' => '职位信息错误']);
        }
        //是否是职位协作人
        $caseModel = new CaseModel();
        $checkResult1 = $caseModel->chkCaseEditRight($caseId);
        $projectModel = new ProjectModel();
        $checkResult2 = $projectModel->chkEditRight($caseInfo['projectid']);
        $customerModel = new CustomerModel();
        $checkResult3 = $customerModel->chkEditSubRight($caseInfo['subid']);
        if (!$checkResult1 && !$checkResult2 && !$checkResult3) {
            return $this->json(['status' => false, 'message' => '您无权编辑客户联系人']);
        }
        $subId = $caseInfo['subid'];
        $sql = 'select 1 from CaseContacter where accountid = ? and subid = ? and status = ?';
        $var = [$accountId,$subId,'01'];
        $result = Db::selectOne($sql,$var);
        if (!empty($result)) {
            return $this->json([
                'status' => 1,
                'message' => '该联系人已被交易公司下的职位绑定，确定删除吗？'
            ]);
        }
        return $this->json([
            'status' => 2,
            'message' => '校验成功'
        ]);
    }

    /**
     * 职位详情页删除客户联系人
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function deleteCustomerAccount(Request $request) {
        $accountId = $request->getParam('accountid');
        $caseId = $request->getParam('caseid');
        $sql = 'select subid,projectid from SCase where caseid = ?';
        $var = [$caseId];
        $caseInfo = Db::selectOne($sql,$var);
        if (empty($caseInfo)) {
            return $this->json(['status' => false, 'message' => '职位信息错误']);
        }
        //是否是职位协作人
        $caseModel = new CaseModel();
        $checkResult1 = $caseModel->chkCaseEditRight($caseId);
        $projectModel = new ProjectModel();
        $checkResult2 = $projectModel->chkEditRight($caseInfo['projectid']);
        $customerModel = new CustomerModel();
        $checkResult3 = $customerModel->chkEditSubRight($caseInfo['subid']);
        if (!$checkResult1 && !$checkResult2 && !$checkResult3) {
            return $this->json(['status' => false, 'message' => '您无权编辑客户联系人']);
        }
        $subId = $caseInfo['subid'];
        $result = (new AccountModel())->lock($accountId, $subId);
        return $this->json(
            [
                'status' => $result == 1,
                'message' => $result == 1 ? '修改成功' : '修改失败',
            ]
        );
    }


}